package com.rfid.config;

import android.text.TextUtils;

import com.google.gson.Gson;
import com.rfid.util.FileUtil;
import com.rfid.util.LogUtils;

import java.io.File;

public class ConfigManager {

    private static final String TAG = "ConfigManager";

    private  static ConfigManager mConfigManager;

    private Config mConfig;


    public  static ConfigManager getInstance() {
        if(mConfigManager == null) {
            mConfigManager = new ConfigManager();
        }
        return mConfigManager;
    }

    public Config getConfig() {
        if(mConfig == null) {
            initConfig(Constant.CONFIG_PATH);
        }
        return mConfig;
    }

    public void initConfig(String path) {
        File file = new File(path);
        if(!file.exists()) {
            makeConfig(path);
            return;
        }
        String json = FileUtil.readFile(path);
        if(TextUtils.isEmpty(json)) {
            LogUtils.v(TAG,"int fail.Can not read config file");
            return;
        }
        Gson gson = new Gson();
        mConfig = gson.fromJson(json,Config.class);
    }

    private void makeConfig(String path) {
        Config config = new Config();
        config.setBookLabLen(Constant.BOOK_LAB_LEN);
        config.setShelfLabLen(Constant.SHELF_LAB_LEN);
        config.setBaseUrl(Constant.BASE_URL);
        mConfig = config;
        Gson gson = new Gson();
        String json = gson.toJson(config);
        FileUtil.writeFile(path,json);
    }
}
